# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import datetime

from datastore.gears import Bike

from common import unescape
import people_api

def _Gear_Encoder(obj):
    if isinstance(obj, Bike):
        return {"id": obj.id,
                "name": unescape(obj.name),
                "type": obj.type,
                "make": unescape(obj.make),
                "model": unescape(obj.model),
                "year": unescape(obj.year),
                "owner": unescape(obj.owner.name),
                "owner_uid": obj.owner.uid,
                "photourl": unescape(obj.photourl),
                "create_datetime": obj.create_datetime,#.strftime("%Y-%m-%d"),
                "frame": unescape(obj.frame),
                "fork": unescape(obj.fork),
                "wheels": unescape(obj.wheels),
                "components": unescape(obj.components),
                "description": unescape(obj.description),
                }
    elif isinstance(obj, datetime.datetime):
        return obj.isoformat()
    else:
        raise TypeError('%r is not JSON serializable' % obj)
    
def get_bike_types():
    return Bike.Types

def get_bikes_by_uid(request, uid):
    """return user's bikes.
    Args:
      uid: user's id
    Returns:
      bikes: list(bike), list of json serialized bike.
    """
    siteuser = people_api.get_user_by_uid(uid)
    if not siteuser:
        return {"status": "error",
                "bikes": [],
                "message": "can not found user %s"%uid,
                }

    bikes = Bike.get_bikes_by_user(siteuser)
    return {"status": "ok",
            "bikes": bikes,
            "custom_encoder": _Gear_Encoder,
            }

def new_bike(request, type, make, model, year, photourl,
               frame="", fork="", wheels="", components="", description=""):
    """create a bike.
    Args: type, make, model,
          year,photourl,frame,fork,
          wheels,components,description
    Returns:
      bikeid: id of bike.
    """
    user = people_api.get_current_user()
    if not user:
        return {"status": "error",
                "message": "please login first",
                }
    bike = Bike.create(siteuser = user, type=type, make=make, model=model, year=year, photourl=photourl,
               frame=frame, fork=fork, wheels=wheels, components=components, description=description)
    result = {"status": "ok",
              "bikeid": bike.id}
    return result

def remove_bike(request, bikeid):
    """remove a bike.
    Args:
      bikeid: id of bike.
    Returns:
      None
    """
    user = people_api.get_current_user()
    if not user:
        return {"status": "error",
                "message": "please login first",
                }
    bike = Bike.get_by_id(long(bikeid))
    if not bike:
        return {"status": "error",
                "message": "can not find bike"}

    if bike.owner.uid != user.uid:
        return {"status": "error",
                "message": "you can not remove others' bike"}

    Bike.remove(bike)
    result = {"status": "ok"}
    return result

def get_bike_by_id(request, bikeid):
    """get a bike.
    Args:
      bikeid: bike's id
    Returns:
      bike: json serialized bike.
    """
    bikeid = long(bikeid)
    bike = Bike.get_by_id(bikeid)
    if bike:
        return {"status": "ok",
                "bike": bike,
                "custom_encoder": _Gear_Encoder}
    else:
        return {"status": "error",
                "message": "can not find bike"}

def main():
    pass

if __name__ == '__main__':
    main()
